package com.code.link;

public class LinkedList {
    /**
     * 对链表中都一个链结点的引用
     * 从first出发，沿着链表通过每个链结点的next字段，就可以找到其他链结点。
     */
    private Link first;

    public LinkedList() {
        first = null;
    }

    public boolean isEmpty() {
        return first == null;
    }

    /**
     * 在链表的开头插入新的节点
     *
     * @param id
     * @param dd
     */
    public void insertFirst(int id, double dd) {
        Link newLink = new Link(id, dd);
        //newLink --> old first
        newLink.next = first;
        //first --> newLink
        first = newLink;
    }

    /**
     * 删除第一个节点
     * Java中，该删除的节点将被垃圾收集器进程在某个时刻销毁。
     *
     * @return 删除的节点
     */
    public Link deleteFirst() {
        Link temp = first;
        first = first.next;
        return temp;
    }


    public void displayList() {
        System.out.println("List {first --> last}: ");
        //current引用当前节点
        Link curent = first;
        while (curent != null) {
            System.out.println(curent.toString());
            curent = curent.next;
        }
    }

    /**
     * 查找指定id的Link
     *
     * @param key
     * @return
     */
    public Link find(int key) {
        Link current = first;
        while (current.iData != key) {
            if (current.next == null) {
                return null;
            } else {
                current = current.next;
            }
        }
        return current;
    }

    public Link delete(int key) {
        Link current = first;
        Link previous = first;
        while (current.iData != key) {
            if (current.next == null) {
                return null;
            } else {
                //移到下一个节点
                previous = current;
                current = current.next;
            }
        }
        //找到匹配的节点
        if (current == first) {
            //如果是第一个节点
            first = first.next;
        } else {
            //删除当前节点，把前一个节点的next引用到当前节点的下一个Link
            previous.next = current.next;
        }
        return current;
    }

}
